﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;

namespace DroughtAnalysis
{
    /// <summary>
    /// Responsible for saving results to DB
    /// </summary>
    public class DatabaseWriter
    {
        /// <summary>
        /// Saves the calculation results to the database
        /// </summary>
        /// <param name="calculatedSiteList">list of calculated sites</param>
        /// <param name="bgWorker">background worker</param>
        /// <param name="e">parameters</param>
        public void SaveResultsToDB(IList<DroughtSiteInfo> calculatedSiteList, DroughtMethodInfo droughtMethod, BackgroundWorker bgWorker, DoWorkEventArgs e)
        {
            bgWorker.ReportProgress(0, "Saving drought indexes to database..");

            int successfulSeries = 0;
            for (int i = 0; i < calculatedSiteList.Count; i++)
            {
                for (int j=0; j < droughtMethod.OutputVariables.Count; j++)
                {
                DroughtSiteInfo result = calculatedSiteList[i];

                    try
                    {
                        int percent = (int)((i + 1) * 100 / calculatedSiteList.Count);
                        string message = String.Format("Writing to Database: {0} ({1}/{2})", result.Site.Name, i, calculatedSiteList.Count);
                        bgWorker.ReportProgress(percent, message);

                        DroughtTimeSeriesWriter writer = new DroughtTimeSeriesWriter();
                        writer.DroughtVariableName = droughtMethod.OutputVariables[j].Name;
                        writer.IndexColumnName = droughtMethod.OutputVariables[j].Speciation;
                        writer.IndexFileName = droughtMethod.OutputFiles[j];
                        writer.DroughtMethodName = droughtMethod.MethodName;
                        writer.DroughtMethodUnitName = droughtMethod.OutputVariables[j].VariableUnit.Name;
                        string outputTimeUnitsName = droughtMethod.OutputVariables[j].TimeUnit.Name.ToLower();
                        writer.OutputTimeStep = outputTimeUnitsName;
                        
                        writer.WriteDroughtIndex(result);

                        result.CalculationStatus = RCalculationStatus.DataSavedToDatabase;
                        successfulSeries++;
                    }         
                    catch (Exception ex) 
                    { 
                        bgWorker.ReportProgress(0, "Error: " + ex.Message); 
                    }
                }
            }

            string resultMessage = String.Format("Drought Index calculated for {0} time series.",
                successfulSeries);
            e.Result = new DatabaseSavingResult() { StatusMessage = resultMessage };
        }
    }
}
